package com.jiangore.dao;

import com.jiangore.entity.Member;
import com.jiangore.mapper.MemberRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Todo
 * @Author jiangtao
 * @CreateBy 2020-03-09 1:48 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Repository
public class MemberDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Member getById(int id) {
        String sql = "select * from a_member where id = ?";
        Member m = jdbcTemplate.queryForObject(sql, new MemberRowMapper(), id);
        return m;
    }

    public int count() {
        String sql = "select count(*) from a_member";
        int count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    public List<Member> getAll() {
        String sql = "select * from a_member";
        List<Member> list = jdbcTemplate.query(sql, new MemberRowMapper());
        return list;
    }

    public int insert(Member m) {
        if (null == m) {
            return 0;
        }
        String sql = "INSERT INTO a_member(account, nickname, password, email, mobile, age, register_time) VALUES (?, ?, ?, ?, ?, ?, ?)";
        int num = jdbcTemplate.update(sql, m.getAccount(), m.getNickname(), m.getPassword(), m.getEmail(),
                m.getMobile(), m.getAge(), m.getRegisterTime());
        return num;
    }

    public int updateById(Member m) {
        if (null == m || m.getId() == null || m.getId().intValue() == 0) {
            return 0;
        }
        String sql = "update a_member set password = ?, email = ? where id = ?";
        int num = jdbcTemplate.update(sql, m.getPassword(), m.getEmail(), m.getId());
        return num;
    }

    public int delete(int id) {
        String sql = "delete from a_member where id = ?";
        int num = jdbcTemplate.update(sql, id);
        return num;
    }
}
